/**
 * 
 */
package template.page.user;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

import org.apache.click.control.ActionButton;
import org.apache.click.control.Column;
import org.apache.click.control.Form;
import org.apache.click.control.HiddenField;
import org.apache.click.control.Option;
import org.apache.click.control.Submit;
import org.apache.click.control.Table;
import org.apache.click.dataprovider.DataProvider;
import org.apache.click.extras.control.CheckList;
import org.apache.click.util.Bindable;

import template.page.BorderPage;
import cvcg.dto.Top5DTO;
import cvcg.model.AttendingPlayer;
import cvcg.model.GameSession;
import cvcg.model.Vote;
import cvcg.util.VoteComparator;
import cvcg.util.VoteResultDecorator;

/**
 * @author jaracje
 *
 */
@SuppressWarnings("serial")
public class GameSessionDetailPhase2 extends BorderPage 
{	 
	public String title = "Phase 2 (Top 5)";
		
	private GameSession currentGameSession;
	private Form form = new Form("form");
	private CheckList sortableCheckList;
	private HiddenField idField = new HiddenField("id",Long.class);
	private Table top5Table = new Table("top5Table");
	private Table votePhase1ResultTable = new Table("votePhase1ResultTable");
	private ActionButton backButton = new ActionButton("backButton","back");
	
	@Bindable protected Long id;
	
	@SuppressWarnings("rawtypes")
	public GameSessionDetailPhase2() 
	{
		
		top5Table.setClass(Table.CLASS_ITS);
		top5Table.setWidth("100%");
		top5Table.setSortable(false);

		top5Table.addColumn(new Column("gameName"));
		top5Table.addColumn(new Column("points"));		
		top5Table.setSortedAscending(false);
		top5Table.setSortedColumn("points");
		
		sortableCheckList = new CheckList("top5Selection", "Game List ");        
        sortableCheckList.addStyleClass("cl2");
        sortableCheckList.setSortable(true);
        sortableCheckList.setStyle("width", "100%;");
        form.add(sortableCheckList);

        form.add(idField);
        form.setFieldStyle("width:20em;");
        form.add(new Submit("save", "  Save  ",  this, "onOkClick"));        
		addControl(backButton);
		backButton.setListener(this, "onBackClick");

        
        // Table rowList will be populated through a DataProvider which loads
	    // data on demand.
        top5Table.setDataProvider(new DataProvider() 
		{	        
			public List getData() 
	        {
				String currentUser = getCurrentUser();
				return getUserCurrentTop5(currentUser);	        
	        }
	    });                
	}
	
	@Override
	public void onGet() 
	{
		idField.setValueObject(id);  
	}
	
	@Override
	public void onInit() 
	{	
		super.onInit();
		
		 List<Option> top5Options = new ArrayList<Option>();
		 List<Vote> topVotes;
		 Set<Long> top5GameIds = new HashSet<Long>();
		 List<String> top5SelectedValues = new ArrayList<String>();
		 Set<Long> voteGameIds = new HashSet<Long>();
		 Set<Vote> gameVotes;
		
		String currentUser = getCurrentUser();
		currentGameSession = getGameSessionService().getGameSessionById(id);
		if (currentGameSession!=null) 
		{
			if (currentGameSession.isPlayerAttendingSession(currentUser)) 
			{
		        addControl(form);
		        addControl(top5Table);
				topVotes = currentGameSession.getTopVotesByPlayerName(currentUser);
				Collections.sort(topVotes,new VoteComparator());
				gameVotes = currentGameSession.getVotes();					
				for (Vote vote : topVotes) 
				{
					top5Options.add(new Option(vote.getGameId(),vote.getGameName()));
					top5GameIds.add(vote.getGameId());	
					top5SelectedValues.add(vote.getGameId().toString());
				}
				for (Vote vote : gameVotes) 
				{
					if (!top5GameIds.contains(vote.getGameId()) && !voteGameIds.contains(vote.getGameId())) 
					{									
						top5Options.add(new Option(vote.getGameId(),vote.getGameName()));
						voteGameIds.add(vote.getGameId());
					}
				}
				
				sortableCheckList.setOptionList(top5Options);
				sortableCheckList.setSelectedValues(top5SelectedValues);
			} else {
				votePhase1ResultTable();
				addControl(votePhase1ResultTable);
			}
		}
	}	
	
	public boolean onOkClick() 
	{
		Map<String,Long> param = new HashMap<String,Long>();
		param.put("id",(Long) idField.getValueObject());
		List<String> selectedValues = sortableCheckList.getSelectedValues();
		List<String> sortOrder = sortableCheckList.getSortorder();
		List<Top5DTO> top5List = new ArrayList<Top5DTO>();
		Top5DTO top5;
		int weight = 5;
		for (String id : sortOrder) 
		{
			if (selectedValues.contains(id)) 
			{
				top5 = new Top5DTO();
				top5.setGameId(Long.valueOf(id));
				top5.setPoints(Integer.valueOf(weight));
				top5List.add(top5);
				weight--;
			}
		}
		String currentUser = getCurrentUser();
		gameSessionService.saveTop5((Long) idField.getValueObject(), currentUser, top5List);
		setRedirect(GameSessionDetailPhase2.class,param);
		return true;
	}
	
	private List<Top5DTO> getUserCurrentTop5(String userName) 
	{
		List<Top5DTO> list = new ArrayList<Top5DTO>();
		Top5DTO top5;
		if (currentGameSession!=null) 
    	{
    		List<Vote> votes = currentGameSession.getTopVotesByPlayerName(userName);
    		for (Vote vote : votes) 
    		{
    			top5 = new Top5DTO();
    			top5.setGameName(vote.getGameName());
    			top5.setPoints(vote.getWeight());
    			list.add(top5);
			}
    	}
		return list;
	}
	
	@SuppressWarnings("rawtypes")
	public void votePhase1ResultTable() {
		votePhase1ResultTable.setClass(Table.CLASS_ITS);
		votePhase1ResultTable.setShowBanner(false);
		votePhase1ResultTable.setSortable(false);

		SortedSet<AttendingPlayer> attendingPlayers = currentGameSession
				.getAttendingPlayers();
		String playerName;
		votePhase1ResultTable.addColumn(new Column("gameName"));
		Column playerCol;
		for (AttendingPlayer attendingPlayer : attendingPlayers) {
			playerName = attendingPlayer.getPlayerName();
			playerCol = new Column(playerName);
			playerCol.setTextAlign("center");
			playerCol.setDecorator(new VoteResultDecorator(playerName));
			votePhase1ResultTable.addColumn(playerCol);
		}
		Column votes = new Column("votes");
		votes.setTextAlign("center");
		votePhase1ResultTable.addColumn(votes);
		votePhase1ResultTable.setSortedColumn("gameName");

		votePhase1ResultTable.setDataProvider(new DataProvider() {

			public Collection getData() {
				return gameSessionService.getVoteResultForGameSession(id);

			}
		});
	}

	
	/**
     * Handle the back click event.
     */    
    public boolean onBackClick() 
    {
    	setRedirect(HomePage.class);        
        return true;
    }

}
